package pinboard.dataLayer.potocol.op;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import pinboard.dataLayer.ByteArrayConvert;
import pinboard.dataLayer.binPack.BinSerializer;
import pinboard.dataLayer.potocol.renderFormat.AddClipParam;
import pinboard.dataLayer.potocol.renderFormat.AddRemoveStrokeParam;
import pinboard.dataLayer.potocol.renderFormat.ClipTransParam;
import pinboard.dataLayer.potocol.renderFormat.HandShakeParam;

public class RenderClientEncoder {

    public static byte[] handShake(String userId) {
        HandShakeParam hsp = new HandShakeParam();
        hsp.userId = userId;
        hsp.deviceType = 4;

        byte[] bizData = null;
        try {
            bizData = BinSerializer.toBytes(hsp, HandShakeParam.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] result = encode(0, 0, bizData);
        return result;
    }

    public static byte[] AddClip(AddClipParam param) {
        return encodeParam(1, 7, param, AddClipParam.class);
    }

    public static byte[] ClipTrans(ClipTransParam param) {
        return encodeParam(1, 12, param, ClipTransParam.class);
    }

    public static byte[] AddRemoveStroke(AddRemoveStrokeParam param) {
        return encodeParam(1, 13, param, AddRemoveStrokeParam.class);
    }

    private static <T> byte[] encodeParam(int opType, int opCode, T data, Class<T> tClass) {
        byte[] bizData = null;
        try {
            bizData = BinSerializer.toBytes(data, tClass);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] result = encode(opType, opCode, bizData);
        return result;
    }

    private static byte[] encode(int opType, int opCode, byte[] data) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(10 + data.length);
        try {
            baos.write(ByteArrayConvert.int2Bytes(data.length + 6));//总长度
            baos.write(opType);//0為操作協議 1位數據協議
            baos.write(0);//tmpCode 暫時沒有用的一個byte
            baos.write(ByteArrayConvert.int2Bytes(opCode));//握手協議 為Int32的0
            baos.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return baos.toByteArray();
    }
}
